package com.yexx.hotSwapper;


import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import javassist.*;
import javassist.util.HotSwapper;

import java.io.IOException;

/**
 * Description: 热加载测试
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/10/21-11:09
 */
public class HotSwapperTest {

    public static void main(String[] args) throws Exception {

        HotSwapperTest test = new HotSwapperTest();
        test.hotSwapper();


    }

    private void hotSwapper() throws IOException, IllegalConnectorArgumentsException, NotFoundException, CannotCompileException {
        HotSwapperDemo demo = new HotSwapperDemo();
        System.out.println("你到底几个前女友?");
        new Thread(
                () -> {
                    while (true) {
                        System.out.println(demo.findGirlNumber("myles zelic"));
                    }
                }
        ).start();
        //添加监控: VM options : -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
        HotSwapper hotSwapper = new HotSwapper(8000);

        ClassPool classPool = ClassPool.getDefault();
        /**
         * 官方文档是这样说的：
         * The default ClassPool returned by a static method ClassPool.getDefault() searches the same path that the underlying JVM (Java virtual machine) has.
         * If a program is running on a web application server such as JBoss and Tomcat, the ClassPoolobject may not be able to find user classes since such a web application server
         * uses multiple class loaders as well as the system class loader. In that case, an additional class path must be registered to the ClassPool.
         * 翻译：
         * 由静态方法ClassPool.getDefault()返回的默认的ClassPool搜索与底层JVM(Java虚拟机)相同的路径。
         * 如果一个程序在像JBoss和Tomcat这样的web应用程序服务器上运行，那么ClassPoolobject可能无法找到用户类，因为这样的web应用程序服务器
         * 使用了多个类加载器和系统类装入器。在这种情况下，必须向ClassPool注册一个额外的类路径。
         */
        //修复javassit不生效的问题 -- start
        ClassClassPath classPath = new ClassClassPath(HotSwapperTest.class);
        classPool.insertClassPath(classPath);
        //修复javassit不生效的问题 -- end
        CtClass ctClass = classPool.get(HotSwapperDemo.class.getName());

        CtMethod findGirlNumber = ctClass.getDeclaredMethod("findGirlNumber");

        //重写方法
        findGirlNumber.setBody("{return $1 + \"的前女友数量为:\" + 0 + \"个\" ;}");
        //重载热插拔
        hotSwapper.reload(HotSwapperDemo.class.getName(), ctClass.toBytecode());
        ctClass.writeFile("com/yexx/hotswapper");
        System.out.println("::执行HotSwapper热插拔,修改数量0成功!!!!");
    }

}
